from collections import namedtuple
from collections import deque
from collections import defaultdict
from collections import OrderedDict
from collections import ChainMap
from collections import Counter
import os
import argparse
# ----------------------命名tuple namedtuple('名称', [属性list])-------------
Point = namedtuple("Point", ["x", "y"])
p1 = Point(1, 2)
print(p1.x)
print(type(p1))
print(isinstance(p1, tuple))
Circle = namedtuple("Circle", ["x", "y", "r"])
# ----------------------双向列表------------------------------------------------
deq = deque(["a", "b", "c"])
deq.append("x")
deq.pop()
deq.appendleft("y")  # 头部添加元素
deq.popleft()  # 头部删除元素
print(deq)
# -----------------使用defaultdict可以在key不存在时，返回一个默认值，且不抛出KeyError。
dd = defaultdict(lambda: "N/A")  # 设置无key时的默认值
dd["key"] = "value"
print(dd["key"])
print(dd["key2"])
# ---------------OrderedDict有序KeyDict-有序是指Key按照插入顺序排列--------
d = dict([('a', 2), ('c', 1), ('b', 3), ('e', 7), ('d', 5)])
d["f"] = 6
print(d.keys())
od = OrderedDict([('a', 1), ('c', 2), ('b', 3), ('e', 4), ('d', 5)])
od["f"] = 6
print(od.keys())


class LastUpdatedOrderedDict(OrderedDict):
    """
    OrderedDict可以实现一个FIFO（先进先出）的dict，当容量超出限制时，先删除最早添加的Key
    """
    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self._capacity:
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value)


# -----------ChainMap可以把一组dict串起来并组成一个逻辑上的dict。-----------------
# ----------ChainMap本身也是一个dict，查找时，会按照顺序在内部的dict依次查找。----
defaults = {
    "color": "green",
    "user": "Tom"
}
parse = argparse.ArgumentParser()  # 构造命令行参数
parse.add_argument("-u", "--user")
parse.add_argument("-c", "--color")
namespace = parse.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v}
combined = ChainMap(command_line_args, os.environ, defaults)
print('color=%s' % combined['color'])
print('user=%s' % combined['user'])
# ------------------Counter------------------------------------
c = Counter()
for ch in "programming":
    c[ch] += 1
print(c)